package com.example.demo.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.demo.common.PassToken;
import com.example.demo.enums.RedisPreEnum;
import com.example.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

@Slf4j
public class WebSocketFilter implements HandshakeInterceptor {

    @Resource
    RedisUtil redisUtil;


    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Map<String, Object> map) throws Exception {

        ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;

        String  token = servletServerHttpRequest.getServletRequest().getHeader("token");
        if (token==null){
            throw new RuntimeException("无token,请重新登录");
        }
        String userId;
        try{
            userId= JWT.decode(token).getAudience().get(0);
            System.out.println(userId);
        }catch (JWTDecodeException e){
            throw new RuntimeException("token无效");
        }
        String  key = RedisPreEnum.JWT_TOKEN_PRE.getPre()+userId;
        if (!redisUtil.get(key).toString().equals(token)){
            log.info("key:"+redisUtil.get(key).toString()+"\n"+"token:"+token);
            throw  new RuntimeException("token无效");
        }
        else if (redisUtil.getExpireByKey(key)<300L){
            redisUtil.expire(key,7200L);
        }

        return true;

    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
